var express = require('express');
const md5 = require('md5');
const jwt = require('jsonwebtoken');
var UserModel = require('../../models/UserModel');
const {secret} = require('../../config/config');

var router = express.Router();






router.post('/login', (req, res) => {
    let { username, password } = req.body;
    UserModel.findOne({ username: username, password: md5(password) })
        .then((data) => {
            if (data) {
                //创建token
                let token = jwt.sign(
                    {
                        username: data.username,
                        _id: data._id
                    },
                    secret,
                    {
                        expiresIn: 60 * 60 * 24
                    }
                )
                res.json({
                    code: '0000',
                    msg: '登录成功',
                    data: token
                })
            } else {
                return res.json({
                    code: '2002',
                    msg: '账号/密码错误',
                    data: null
                })
            }

        })
        .catch(() => {
            res.json({
                code: '2001',
                msg: '数据库读取失败',
                data: null
            })
        })
})


router.post('/logout', (req, res) => {
    req.session.destroy(() => {
        res.render('success', { msg: '退出成功', url: '/login' })
    });
})

module.exports = router;
